package com.cugbmao.lucene;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Indexer
{
	private final IndexWriter	writer;

	public Indexer(final Directory dir) throws IOException
	{
		// Directory dir = FSDirectory.open(new File(indexDir));
		IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_43,
				new StandardAnalyzer(Version.LUCENE_43));
		conf.setOpenMode(OpenMode.CREATE);
		writer = new IndexWriter(dir, conf);
	}

	public void close() throws IOException
	{
		writer.close();
	}

	public static void main(final String[] args) throws Exception
	{
		if (args.length != 2)
		{
			throw new Exception("Usage: java " + Indexer.class.getName()
					+ " <index dir> <data dir>");
		}

		File indexDir = new File(args[0]);
		File dataDir = new File(args[1]);
		Indexer indexer = new Indexer(FSDirectory.open(indexDir));

		long start = System.currentTimeMillis();
		int numIndexed = 0;
		try
		{
			numIndexed = indexer.index(indexDir, dataDir);
		}
		finally
		{
			indexer.close();
		}
		long end = System.currentTimeMillis();

		System.out.println("Indexing " + numIndexed + " files took "
				+ (end - start) + " milliseconds");
	}

	public int index(final File indexDir, final File dataDir)
			throws IOException
	{
		if (!dataDir.exists() || !dataDir.isDirectory())
		{
			throw new IOException(dataDir
					+ " does not exist or is not a directory");
		}
		indexDirectory(writer, dataDir);
		return writer.numDocs();
	}

	private void indexDirectory(final IndexWriter writer, final File dir)
			throws IOException
	{
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++)
		{
			File file = files[i];
			if (file.isDirectory())
			{
				indexDirectory(writer, file);
			}
			else
			{
				indexFile(writer, file);
			}
		}
	}

	private void indexFile(final IndexWriter writer, final File file)
			throws IOException
	{
		if (file.isHidden() || !file.exists() || !file.canRead())
		{
			return;
		}

		System.out.println("Indexing " + file.getCanonicalPath());

		Document doc = new Document();
		Field fieldName = new StringField("filename", file.getName(),
				Field.Store.YES);
		Field fieldContent = new TextField("contents", new FileReader(file));
		Field fieldPath = new StringField("fullpath", file.getCanonicalPath(),
				Field.Store.YES);

		doc.add(fieldName);
		doc.add(fieldContent);
		doc.add(fieldPath);
		writer.addDocument(doc);
	}
}
